<template>
  <div class="uploads-container">
    <h2>文件管理</h2>

    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="文件类型">
          <el-select v-model="searchForm.relatedType" placeholder="请选择文件类型" clearable>
            <el-option label="活动图片" :value="0" />
            <el-option label="新闻图片" :value="1" />
            <el-option label="社团图片" :value="2" /> <!-- 修改社团图片选项的值 -->
          </el-select>
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 上传区域 -->
    <div class="upload-section">
      <el-form :inline="true" :model="uploadForm">
        <el-form-item label="文件类型" required>
          <el-select v-model="uploadForm.relatedType" placeholder="请选择文件类型" @change="handleTypeChange">
            <el-option label="活动图片" :value="0" />
            <el-option label="新闻图片" :value="1" />
            <el-option label="社团图片" :value="2" /> <!-- 修改社团图片选项的值 -->
          </el-select>
        </el-form-item>
        <el-form-item label="关联内容" required>
          <el-select
            v-model="uploadForm.relatedId"
            :placeholder="uploadForm.relatedType === 0 ? '请选择活动' : uploadForm.relatedType === 1 ? '请选择新闻' : '请选择社团'"
            filterable
          >
            <el-option
              v-for="item in relatedList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <el-upload
        class="upload-demo"
        action="http://localhost:8080/file/upload"
        :headers="headers"
        :data="{
          relateType: uploadForm.relatedType,
          relateId: uploadForm.relatedId
        }"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :disabled="uploadForm.relatedType === null || uploadForm.relatedId === null"
        multiple
        list-type="picture"
        name="file"
      >
        <el-button
          type="primary"
          :disabled="uploadForm.relatedType === null || uploadForm.relatedId === null"
        >
          上传文件
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 jpg/png 文件，且不超过 5MB
          </div>
        </template>
      </el-upload>
    </div>

    <!-- 文件列表 -->
    <div class="file-list">
      <el-table :data="fileList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="fileName" label="文件名" />
        <el-table-column label="文件类型" width="100">
          <template #default="scope">
            {{ scope.row.relatedType === 0 ? '活动图片' : scope.row.relatedType === 1 ? '新闻图片' : '社团图片' }}
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="filePath" label="预览图" width="200">
          <template #default="scope">
            <el-image
              style="width: 180px; height: 100px"
              :src="scope.row.filePath"
              fit="cover"
              :preview-src-list="[scope.row.filePath]"
              :preview-teleported="true"
            />
          </template>
        </el-table-column>
        <el-table-column prop="uploadedAt" label="上传时间" />
        <el-table-column label="关联内容" width="200">
          <template #default="scope">
            <span>{{ getRelatedTitle(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="previewImage(scope.$index, scope.row)"
            >
              复制链接
            </el-button>
            <el-button
              type="danger"
              link
              @click="deleteFile(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const fileList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 上传表单
const uploadForm = reactive({
  relatedType: null,
  relatedId: null
})

// 搜索表单
const searchForm = reactive({
  relatedType: '',
  uploadedAtStart: '',  // 替换 startTime
  uploadedAtEnd: ''     // 替换 endTime
})

// 关联内容列表
const relatedList = ref([])

// 关联内容标题缓存
const relatedTitleMap = reactive({
  activities: new Map(),
  news: new Map(),
  clubs: new Map() // 新增社团标题缓存
})

// 修改上传URL的计算属性
const uploadUrl = computed(() => '/file/upload')

// 修改请求头计算属性，只保留 token
const headers = computed(() => ({
  'token': localStorage.getItem('token')
}))

// 日期范围
const dateRange = ref([])

// 处理日期变化
const handleDateChange = (val) => {
  if (val) {
    searchForm.uploadedAtStart = val[0]
    searchForm.uploadedAtEnd = val[1]
  } else {
    searchForm.uploadedAtStart = ''
    searchForm.uploadedAtEnd = ''
  }
}

// 处理文件类型变化
const handleTypeChange = async (value) => {
  uploadForm.relatedId = null // 清空已选择的关联ID
  await loadRelatedList(value)
}

// 加载关联内容列表
const loadRelatedList = async (type) => {
  try {
    let url, map
    if (type === 0) {
      url = '/activity/loadDataList'
      map = relatedTitleMap.activities
    } else if (type === 1) {
      url = '/news/admin/loadDataList'
      map = relatedTitleMap.news
    } else if (type === 2) { // 修改社团图片类型的值
      url = '/club/loadDataList'
      map = relatedTitleMap.clubs
    }
    const res = await axios.get(url, {
      params: {
        pageSize: 1000
      }
    })
    if (res.data.status === 'success') {
      relatedList.value = res.data.data.list.map(item => ({
        id: item.id,
        title: item.name // 社团名称字段为name
      }))

      // 更新标题缓存
      relatedList.value.forEach(item => {
        map.set(item.id, item.title)
      })
    }
  } catch (error) {
    console.error('获取关联内容列表失败:', error)
    ElMessage.error('获取关联内容列表失败')
  }
}

// 获取关联内容标题
const getRelatedTitle = (row) => {
  let map
  if (row.relatedType === 0) {
    map = relatedTitleMap.activities
  } else if (row.relatedType === 1) {
    map = relatedTitleMap.news
  } else if (row.relatedType === 2) { // 修改社团图片类型的值
    map = relatedTitleMap.clubs
  }
  return map.get(row.relatedId) || `${row.relatedType === 0 ? '活动' : row.relatedType === 1 ? '新闻' : '社团'}(ID: ${row.relatedId})`
}

// 加载文件列表
const loadFiles = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }

    const res = await axios.get('/file/list', { params })
    if (res.data.status === 'success') {
      fileList.value = res.data.data.list
      total.value = res.data.data.totalCount

      // 获取所有需要的活动、新闻和社团信息
      const activityIds = new Set()
      const newsIds = new Set()
      const clubIds = new Set() // 新增社团ID集合
      fileList.value.forEach(file => {
        if (file.relatedType === 0) {
          activityIds.add(file.relatedId)
        } else if (file.relatedType === 1) {
          newsIds.add(file.relatedId)
        } else if (file.relatedType === 2) { // 修改社团图片类型的值
          clubIds.add(file.relatedId)
        }
      })

      // 如果有活动相关的文件，加载活动信息
      if (activityIds.size > 0) {
        const activityRes = await axios.get('/activity/loadDataList', {
          params: {
            ids: Array.from(activityIds).join(',')
          }
        })
        if (activityRes.data.status === 'success') {
          activityRes.data.data.list.forEach(activity => {
            relatedTitleMap.activities.set(activity.id, activity.title)
          })
        }
      }

      // 如果有新闻相关的文件，加载新闻信息
      if (newsIds.size > 0) {
        const newsRes = await axios.get('/news/admin/loadDataList', {
          params: {
            ids: Array.from(newsIds).join(',')
          }
        })
        if (newsRes.data.status === 'success') {
          newsRes.data.data.list.forEach(news => {
            relatedTitleMap.news.set(news.id, news.title)
          })
        }
      }

      // 如果有社团相关的文件，加载社团信息
      if (clubIds.size > 0) { // 修改社团图片类型的值
        const clubRes = await axios.get('/club/loadDataList', {
          params: {
            ids: Array.from(clubIds).join(',')
          }
        })
        if (clubRes.data.status === 'success') {
          clubRes.data.data.list.forEach(club => {
            relatedTitleMap.clubs.set(club.id, club.name)
          })
        }
      }
    }
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  currentPage.value = 1
  loadFiles()
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  dateRange.value = []  // 清空日期选择器
  currentPage.value = 1
  loadFiles()
}

// 上传相关方法
const handleUploadSuccess = (response) => {
  console.log('Upload success:', response)  // 添加日志
  if (response.status === 'success') {
    ElMessage.success('上传成功')
    loadFiles()
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleUploadError = (error) => {
  console.error('Upload error:', error)  // 添加日志
  ElMessage.error('上传失败: ' + (error.message || '未知错误'))
}

const beforeUpload = (file) => {
  console.log('Before upload:', file)  // 添加日志
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 修改复制链接方法
const previewImage = (index, row) => {
  // 只保留复制功能
  navigator.clipboard.writeText(row.filePath).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 删除文件
const deleteFile = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
      type: 'warning'
    })
    const res = await axios.post('/file/delete', null, {
      params: {
        id: id
      }
    })
    if (res.data.status === 'success') {
      ElMessage.success('删除成功')
      loadFiles()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else {
    return (size / 1024 / 1024).toFixed(2) + ' MB'
  }
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  loadFiles()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadFiles()
}

onMounted(() => {
  loadFiles()
})
</script>

<style scoped>
.uploads-container {
  padding: 20px;
}

.toolbar,
.upload-section,
.file-list {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-upload-list--picture) {
  margin-top: 20px;
}

.el-upload__tip {
  margin-top: 8px;
  color: #666;
}
</style>